package com.wlyuan.index.remote.consumer;

import com.wlyuan.index.api.IWaybillIndexService;
import com.wlyuan.index.remote.message.BillMessage;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author yuanjie
 */
@Slf4j
@Component
public class BillMessageConsumer extends AbstractMessageConsumer<BillMessage> {
    @Resource
    private IWaybillIndexService waybillIndexService;

    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = Queues.BILL_REINDEX),
            exchange = @Exchange(value = Exchanges.FINANCE),
            key = {"BillSpecDeleted"})
    }, concurrency = "4")
    public void consumeSome(String string) {
        if (logger.isDebugEnabled()) {
            logger.debug("~收到账单消息: {}", string);
        }
        try {
            this.handle(string, BillMessage.class, message -> {
                var bill = message.getBillIndex();
                if (CollectionUtils.isEmpty(bill.getWaybillIds())) {
                    logger.warn("Bill waybills empty: {}", bill);
                    return;
                }
                waybillIndexService.reindexAll(bill.getWaybillIds());
            });
        } catch (Exception e) {
            logger.error("处理账单消息失败：{}", string, e);
        }
    }

    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = Queues.BILL),
            exchange = @Exchange(value = Exchanges.FINANCE),
            key = {
                    "BillCreated", "BillSent", "BillClosed", "BillRecalled",
                    "BillRefused", "BillSpecAdded", "BillFinished"
            })
    }, concurrency = "50")
    public void consume(String string) {
        if (logger.isDebugEnabled()) {
            logger.debug("收到账单消息: {}", string);
        }
        try {
            this.handle(string, BillMessage.class, message -> {
                var bill = message.getBillIndex();
                waybillIndexService.index(bill);
            });
        } catch (Exception e) {
            logger.error("处理账单消息失败：{}", string, e);
        }
    }
}
